# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-04 23:38
# File     : language_specs.py
# Project  : codebuddy_craft
# Desc     : 语言规范

import os
import json
from typing import Dict, List, Optional, Any

class LanguageSpecManager:
    """编程语言规范管理器
    
    负责加载和提供各种编程语言的规范信息，如语法规则、最佳实践等
    """
    
    def __init__(self, specs_dir: Optional[str] = None):
        """初始化语言规范管理器
        
        Args:
            specs_dir: 规范目录路径，默认为None，将使用默认路径
        """
        self.specs_dir = specs_dir or os.path.join(
            os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
            "resources", "language_specs"
        )
        self.language_specs: Dict[str, Dict[str, Any]] = {}
        self._load_specs()
    
    def _load_specs(self) -> None:
        """加载所有语言规范文件"""
        if not os.path.exists(self.specs_dir):
            os.makedirs(self.specs_dir, exist_ok=True)
            
        # 遍历规范目录加载所有JSON规范文件
        for root, _, files in os.walk(self.specs_dir):
            for file in files:
                if file.endswith('.json'):
                    try:
                        file_path = os.path.join(root, file)
                        language = os.path.splitext(os.path.basename(file))[0]
                        
                        with open(file_path, 'r', encoding='utf-8') as f:
                            spec_data = json.load(f)
                            self.language_specs[language] = spec_data
                    except Exception as e:
                        print(f"Error loading language spec {file}: {str(e)}")
    
    def get_language_spec(self, language: str) -> Dict[str, Any]:
        """获取指定编程语言的规范
        
        Args:
            language: 编程语言名称，如 'python', 'javascript', 'typescript'
            
        Returns:
            包含语言规范信息的字典
        """
        # 尝试精确匹配
        if language.lower() in self.language_specs:
            return self.language_specs[language.lower()]
        
        # 尝试部分匹配
        for lang_name in self.language_specs:
            if language.lower() in lang_name.lower():
                return self.language_specs[lang_name]
        
        # 返回默认规范
        return self._get_default_spec()
    
    def _get_default_spec(self) -> Dict[str, Any]:
        """获取默认语言规范
        
        Returns:
            默认语言规范字典
        """
        return {
            "name": "generic",
            "file_extension": ".txt",
            "comment_style": {
                "line": "//",
                "block_start": "/*",
                "block_end": "*/"
            },
            "indentation": "    ",
            "best_practices": [
                "使用有意义的变量名",
                "添加适当的注释",
                "保持代码简洁"
            ]
        }
    
    def get_available_languages(self) -> List[str]:
        """获取所有可用的编程语言列表
        
        Returns:
            编程语言名称列表
        """
        return list(self.language_specs.keys())
    
    def get_syntax_highlight(self, language: str, code: str) -> str:
        """获取代码的语法高亮版本（此方法为示例，实际实现可能需要依赖第三方库）
        
        Args:
            language: 编程语言
            code: 源代码
            
        Returns:
            语法高亮后的代码
        """
        # 实际项目中可以集成如Pygments等库实现语法高亮
        # 这里仅返回原始代码
        return code